package com.atguigu.gmall.realtime.utils;

import com.alibaba.druid.pool.DruidPooledConnection;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.atguigu.gmall.realtime.common.GmallConfig;
import org.apache.calcite.avatica.proto.Common;
import redis.clients.jedis.Jedis;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

/**
 * ClassName: DimUtil
 * Package: com.atguigu.gmall.realtime.utils
 * Description:
 *
 * @Author ChenJun(有志男青年)
 * @Create 2023/5/9 19:25
 * @Version 1.0
 */
public class DimUtil {

    public static JSONObject getDimInfo(Connection connection,String tableName,String id) throws Exception {

        //添加redis缓存  查询redis
        Jedis jedis = JedisUtil.getJedis();
        
        String redisKey = "DIM:"+tableName.toUpperCase()+":"+id;
        String dimInfoStr = jedis.get(redisKey);

        if (dimInfoStr != null){

            //设置过期时间
            jedis.expire(redisKey,24 * 3600);

            jedis.close();
            return JSON.parseObject(dimInfoStr);
        }


        //拼接sql
        String sql = "select * from "+ GmallConfig.HBASE_SCHEMA+"."+tableName+" where id = '"+id+"'";

        System.out.println("查询sql为："+sql);

        List<JSONObject> jsonObjects = JDBCUtil.queryList(connection,
                sql, JSONObject.class, false);

        //将数据写入redis作为缓存
        JSONObject dimInfo = jsonObjects.get(0);
        jedis.setex(redisKey,24 * 3600,dimInfo.toJSONString());
        jedis.close();

        return jsonObjects.get(0);
    }


    public static void main(String[] args) throws Exception {

        DruidPooledConnection connection = DruidDSUtil.getPhoenixConn();

        long start = System.currentTimeMillis();

        JSONObject trademark = getDimInfo(connection, "DIM_SKU_INFO", "37");
        long end = System.currentTimeMillis();

        JSONObject trademark2 = getDimInfo(connection, "DIM_SKU_INFO", "37");
        long end2 = System.currentTimeMillis();

        System.out.println(trademark);
        System.out.println(trademark2);
        System.out.println(end - start);
        System.out.println(end2 - end);


        connection.close();
    }
}
